package com.ruoyi.school.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.enums.FileTypeEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.school.convert.PacStudentConverter;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.dto.PacProSkillCertListDTO;
import com.ruoyi.school.domain.vo.AcademicCommonVo;
import com.ruoyi.school.domain.vo.HonorWallTopThreeVo;
import com.ruoyi.school.domain.vo.PacAcademicOutputVo;
import com.ruoyi.school.domain.vo.PacClassInfoVo;
import com.ruoyi.school.enums.AuditStatusEnum;
import com.ruoyi.school.enums.AuditTypeEnum;
import com.ruoyi.school.enums.WallStateEnum;
import com.ruoyi.school.handler.wall.WallTopThree;
import com.ruoyi.school.service.*;
import com.ruoyi.school.mapper.PacProSkillCertMapper;
import com.ruoyi.school.utils.CommonUtils;
import com.ruoyi.system.domain.TableData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * @author jeremylin
 * @description 针对表【pac_pro_skill_cert(专业技能证书)】的数据库操作Service实现
 * @createDate 2025-05-29 17:56:29
 */
@Service
public class PacProSkillCertServiceImpl extends ServiceImpl<PacProSkillCertMapper, PacProSkillCert>
        implements PacProSkillCertService {
    @Resource
    private StudentService studentService;

    @Resource
    private PacCertTypeService pacCertTypeService;

    @Resource
    private PacAuditRecordsService pacAuditRecordsService;

    @Resource
    private PacTeacherService pacTeacherService;

    @Resource
    private PacClassTeacherService pacClassTeacherService;

    /**
     * 获取列表
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public TableData<PacProSkillCert> getList(PacProSkillCertListDTO pacProSkillCert) {
        // 查询学生信息
        Student studentParams = new Student();
        studentParams.setStuName(pacProSkillCert.getStuName());
        studentParams.setStuNum(pacProSkillCert.getStuNum());
        studentParams.setStuClass(pacProSkillCert.getStuClass());

        if(pacProSkillCert.getTeacherType() != null){
            List<PacClassInfoVo> pacClassInfoVos;
            if(pacProSkillCert.getTeacherType() == 0){
                // 获取当前老师绑定的班级id
                pacClassInfoVos = pacClassTeacherService.selectByTeacherByKey(getLoginUser().getUser(),"teacher");
            }else if(pacProSkillCert.getTeacherType() == 1){
                pacClassInfoVos = pacClassTeacherService.selectByTeacherByKey(getLoginUser().getUser(),"teacher2");
            }else{
                pacClassInfoVos = pacClassTeacherService.selectByTeacherByKey(getLoginUser().getUser(),"duizhang");
            }
            if(pacClassInfoVos != null && !pacClassInfoVos.isEmpty()){
                List<Integer> classIds = pacClassInfoVos.stream().map(PacClass::getId).collect(Collectors.toList());
                // 设置当前老师可以查询的班级
                studentParams.setClassIds(classIds);
            }

            if (pacClassInfoVos.isEmpty()) {
                return TableData.<PacProSkillCert>builder()
                        .total(0L)
                        .build();

            }
        }

        List<Student> studentSearch = studentService.selectInfo(studentParams);
        if (!studentSearch.isEmpty()) {
            List<Integer> ids = studentSearch.stream().map(Student::getId).collect(Collectors.toList());
            pacProSkillCert.setStuIds(ids);
        }
//        Student student = PacStudentConverter.INSTANCE.PacProSkillCertListDTO2DoMain(pacProSkillCert);

//        List<Student> list1 = studentService.getList(student);

//        List<Integer> stuIds = list1.stream().map(Student::getId).collect(Collectors.toList());

        startPage();
        List<PacProSkillCert> list = lambdaQuery()
                .in(!pacProSkillCert.getStuIds().isEmpty(),PacProSkillCert::getStuId, pacProSkillCert.getStuIds())
                .eq(Objects.nonNull(pacProSkillCert.getAcTime()), PacProSkillCert::getAcTime, pacProSkillCert.getAcTime())
                .eq(Objects.nonNull(pacProSkillCert.getAcDanwei()), PacProSkillCert::getAcDanwei, pacProSkillCert.getAcDanwei())
                .likeRight(StringUtils.isNotBlank(pacProSkillCert.getAcTitle()), PacProSkillCert::getAcTitle, pacProSkillCert.getAcTitle())
                .eq(Objects.nonNull(pacProSkillCert.getAcWall()), PacProSkillCert::getAcWall, pacProSkillCert.getAcWall())
                .list();

        // 填充学生信息
        List<Long> ids = list.stream().map(PacProSkillCert::getStuId).collect(Collectors.toList());
        List<Student> students = studentService.selectByStuIds(ids);
        Map<Integer, Student> collect = students.stream().collect(Collectors.toMap(Student::getId, item -> item));

        list.forEach(item -> {
            Student stu = collect.get(item.getStuId().intValue());
            item.setStudent(stu);
            PacTeacher academicTeacherInfo = pacTeacherService.getAcademicTeacherInfo(stu.getClassId());
            if(academicTeacherInfo != null){
                item.setAcademicTeacherName(academicTeacherInfo.getTeacherName());
            }

        });

        PageInfo pageInfo = new PageInfo(list);

        TableData<PacProSkillCert> tableData = TableData.<PacProSkillCert>builder()
                .data(list)
                .total(pageInfo.getTotal())
                .build();


        return tableData;
    }

    /**
     * 详情
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public PacProSkillCert getDetails(PacProSkillCert pacProSkillCert) {
        if (pacProSkillCert.getId() == null) {
            throw new BaseException("id不能为空");
        }
        PacProSkillCert pacProSkillCert1 = getById(pacProSkillCert.getId());
        return pacProSkillCert1;
    }

    /**
     * 新增技能证书
     *
     * @param pacProSkillCert
     * @return
     */
    @Transactional
    @Override
    public boolean add(PacProSkillCert pacProSkillCert) {
        Student student = studentService.getById(pacProSkillCert.getStuId());

        validateAdd(pacProSkillCert);
        FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacProSkillCert.getAcFile());
        pacProSkillCert.setAcFileType(fileTypeName.getCode());
        pacProSkillCert.setStuNum(student.getStuNum());
        pacProSkillCert.setStuName(student.getStuName());
        PacTeacher academicTeacherInfo = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if(academicTeacherInfo != null){
            pacProSkillCert.setAcademicTeacherId(academicTeacherInfo.getId().longValue());
        }
        if (save(pacProSkillCert)) {
            PacAuditRecords pacAuditRecords = initAuditRecords(pacProSkillCert, student);
            return pacAuditRecordsService.add(pacAuditRecords);
        }
        return false;
    }


    /**
     * 编辑技能证书
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public boolean edit(PacProSkillCert pacProSkillCert) {
        if (pacProSkillCert.getId() == null) {
            throw new BaseException("id不能为空");
        }

        if (pacProSkillCert.getStuId() == null) {
            throw new BaseException("请选择学生");
        }

        Student student = studentService.getById(pacProSkillCert.getStuId());

        validateAdd(pacProSkillCert);
        if (pacProSkillCert.getAcFile() != null) {
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacProSkillCert.getAcFile());
            pacProSkillCert.setAcFileType(fileTypeName.getCode());
        }
        pacProSkillCert.setStuNum(student.getStuNum());
        pacProSkillCert.setStuName(student.getStuName());

        // 重置审核状态0
        pacProSkillCert.setAcAudit(AuditStatusEnum.UNAUDITED.getCode());

        if (updateById(pacProSkillCert)) {
            PacAuditRecords pacAuditRecords = initAuditRecords(pacProSkillCert, student);
            return pacAuditRecordsService.updateByRecord(pacAuditRecords);
        }
        return false;
    }

    /**
     * 删除技能证书
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public boolean delete(PacProSkillCert pacProSkillCert) {
        if (pacProSkillCert.getId() == null) {
            throw new BaseException("id不能为空");
        }
        if (removeById(pacProSkillCert.getId())) {
            PacAuditRecords pacAuditRecords = new PacAuditRecords();
            pacAuditRecords.setAuditRecordId(pacProSkillCert.getId());
            pacAuditRecordsService.deleteByOutPutId(pacProSkillCert.getId(), AuditTypeEnum.PAC_WALL_SKILL_CERT.getCode());
        }
        return false;
    }

    /**
     * 审核技能证书
     *
     * @param pacProSkillCert
     */
    @Override
    public void audit(PacProSkillCert pacProSkillCert) {
        if (pacProSkillCert.getId() == null) {
            throw new BaseException("id不能为空");
        }
        if (pacProSkillCert.getAcAudit() == null) {
            throw new BaseException("审核状态不能为空");
        }
        updateById(pacProSkillCert);
    }

    /**
     * 上墙
     *
     * @param academicCommonVo
     * @return
     */
    @Override
    public boolean wall(AcademicCommonVo academicCommonVo) {
        if (extractedFunc(academicCommonVo, 2)) return true;
        return false;
    }

    /**
     * 下墙
     *
     * @param academicCommonVo
     * @return
     */
    @Override
    public boolean unWall(AcademicCommonVo academicCommonVo) {
        if (extractedFunc(academicCommonVo, 1)) return true;
        return false;
    }

    /**
     * 学生-获取我的技能证书列表
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public List<PacProSkillCert> myList(PacProSkillCert pacProSkillCert) {
        Student student = CommonUtils.getStudent();
        if (student != null) {
            List<PacProSkillCert> list = lambdaQuery()
                    .likeRight(StringUtils.isNotEmpty(pacProSkillCert.getAcTitle()),
                            PacProSkillCert::getAcTitle, pacProSkillCert.getAcTitle())
                    .eq(Objects.nonNull(pacProSkillCert.getAcAudit()), PacProSkillCert::getAcAudit, pacProSkillCert.getAcAudit())
                    .eq(Objects.nonNull(pacProSkillCert.getAcFileType()), PacProSkillCert::getAcFileType, pacProSkillCert.getAcFileType())
                    .eq(PacProSkillCert::getStuId, student.getId())
                    .between(Objects.nonNull(pacProSkillCert.getStartTime()), PacProSkillCert::getCreateTime, pacProSkillCert.getStartTime(), pacProSkillCert.getEndTime())
                    .list();
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 学生新增电子证书
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public boolean addMy(PacProSkillCert pacProSkillCert) {
        Student student = CommonUtils.getStudent();

        if (student == null) {
            throw new BaseException("学生帐号信息异常");
        }
//        PacCertType byId = pacCertTypeService.getById(pacProSkillCert.getCertTypeId());

        pacProSkillCert.setStuId(Long.valueOf(student.getId()));
        pacProSkillCert.setStuName(student.getStuName());
//        pacProSkillCert.setAcLevel(byId.getCertLevel());

        return add(pacProSkillCert);
    }

    /**
     * 学生编辑电子证书
     *
     * @param pacProSkillCert
     * @return
     */
    @Override
    public boolean updateMy(PacProSkillCert pacProSkillCert) {
        if (pacProSkillCert.getId() == null) {
            throw new BaseException("id不能为空");
        }
        Student student = CommonUtils.getStudent();

        if (student == null) {
            throw new BaseException("学生帐号信息异常");
        }
        pacProSkillCert.setStuId(Long.valueOf(student.getId()));
        pacProSkillCert.setStuName(student.getStuName());

        return edit(pacProSkillCert);
    }

    /**
     * 获取前三
     *
     * @param builder
     * @return
     */
    @Override
    public List<HonorWallTopThreeVo> getTopThree(WallTopThree builder) {
        List<PacProSkillCert> list = lambdaQuery()
                .eq(PacProSkillCert::getAcWall, WallStateEnum.WALL_STATE_YES.getCode())
                .eq(Objects.nonNull(builder.getFileType()), PacProSkillCert::getAcFileType, builder.getFileType())
                .eq(Objects.nonNull(builder.getStuId()), PacProSkillCert::getStuId, builder.getStuId())
                .between(Objects.nonNull(builder.getStartTime()), PacProSkillCert::getCreateTime, builder.getStartTime(), builder.getEndTime())
                .orderByDesc(PacProSkillCert::getCreateTime)
                .last("LIMIT 3")
                .list();

        if (list != null && !list.isEmpty()) {
            return list.stream().map(item -> {
                HonorWallTopThreeVo honorWallTopThreeVo = new HonorWallTopThreeVo();
                honorWallTopThreeVo.setAcTitle(item.getAcTitle());
                honorWallTopThreeVo.setAcFile(item.getAcFile());
                honorWallTopThreeVo.setAcFileType(item.getAcFileType());
                honorWallTopThreeVo.setStuName(item.getStuName());
                return honorWallTopThreeVo;
            }).collect(Collectors.toList());
        }

        return new ArrayList<>();
    }

    /**
     * 获取学生的荣誉列表
     *
     * @param wallTopThree
     * @return
     */
    @Override
    public List<HonorWallTopThreeVo> getStuHonorList(WallTopThree wallTopThree) {
        List<PacProSkillCert> list = lambdaQuery()
                .eq(Objects.nonNull(wallTopThree.getFileType()), PacProSkillCert::getAcFileType, wallTopThree.getFileType())
                .eq(Objects.nonNull(wallTopThree.getStuId()), PacProSkillCert::getStuId, wallTopThree.getStuId())
                .orderByDesc(PacProSkillCert::getCreateTime)
                .list();

        if (list != null && !list.isEmpty()) {
            return list.stream().map(item -> {
                HonorWallTopThreeVo honorWallTopThreeVo = new HonorWallTopThreeVo();
                honorWallTopThreeVo.setAcTitle(item.getAcTitle());
                honorWallTopThreeVo.setAcFile(item.getAcFile());
                honorWallTopThreeVo.setAcFileType(item.getAcFileType());
                honorWallTopThreeVo.setStuName(item.getStuName());
                return honorWallTopThreeVo;
            }).collect(Collectors.toList());
        }

        return new ArrayList<>();
    }

    @Override
    public long countByAudit() {
        long count = lambdaQuery().eq(PacProSkillCert::getAcAudit, 2).count();
        return count;
    }

    @Override
    public List<PacProSkillCert> selectStuTop5(Integer id) {
        List<PacProSkillCert> list = lambdaQuery()
                .eq(PacProSkillCert::getAcFileType, FileTypeEnum.IMAGE.getCode())
                .eq(PacProSkillCert::getAcAudit, AuditStatusEnum.AUDITED.getCode())
                .eq(PacProSkillCert::getStuId, id)
                .orderByDesc(PacProSkillCert::getCreateTime)
                .last("LIMIT 5")
                .list();

        return list;
    }

    private boolean extractedFunc(AcademicCommonVo academicCommonVo, int acWall) {
        List<Long> ids = academicCommonVo.getIds();
        if (ids != null && !ids.isEmpty()) {
            List<PacProSkillCert> list = new ArrayList<>();
            ids.forEach(item -> {
                PacProSkillCert pacAcademicOutput = new PacProSkillCert();
                pacAcademicOutput.setId(item);
                pacAcademicOutput.setAcWall(acWall);
                list.add(pacAcademicOutput);
            });
            if (updateBatchById(list)) {
                return true;
            }
        }
        return false;
    }


    /***************************************私有方法***************************************/

    /**
     * 初始化，审批实体
     *
     * @param pacProSkillCert
     * @param student
     * @return
     */
    private PacAuditRecords initAuditRecords(PacProSkillCert pacProSkillCert, Student student) {
        PacAuditRecords pacAuditRecords = new PacAuditRecords();
        pacAuditRecords.setAuditType(AuditTypeEnum.PAC_WALL_SKILL_CERT.getCode());
        pacAuditRecords.setAuditRecordId(pacProSkillCert.getId());
        pacAuditRecords.setAuditTitle(pacProSkillCert.getAcTitle());
        pacAuditRecords.setAuditStuId(pacProSkillCert.getStuId());
        pacAuditRecords.setAuditStu(student.getStuName());
        pacAuditRecords.setAuditStuClass(student.getStuClass());
        pacAuditRecords.setAuditFile(pacProSkillCert.getAcFile());
        pacAuditRecords.setAuditFileType(pacProSkillCert.getAcFileType());
        return pacAuditRecords;
    }

    private void validateAdd(PacProSkillCert pacProSkillCert) {
        if (pacProSkillCert.getStuId() == null) {
            throw new BaseException("请选择学生");
        }

        if (pacProSkillCert.getAcTitle() == null) {
            throw new BaseException("请填写技能证书名称");
        }

        if (pacProSkillCert.getAcFile() == null) {
            throw new BaseException("请上传证书证明材料");
        }

//        if (pacProSkillCert.getCertTypeId() == null) {
//            throw new BaseException("请选择技能证书类型");
//        }

//        PacCertType pacCertType = new PacCertType();
//        pacCertType.setId(pacProSkillCert.getCertTypeId());
//        PacCertType type = pacCertTypeService.getDetails(pacCertType);
//
//        if (type == null) {
//            throw new BaseException("技能证书类型不存在");
//        }

//        Integer acPass = pacProSkillCert.getAcPass();
//        if (acPass == null) {
//            throw new BaseException("请选择技能证书等级考试是否通过");
//        }

        // 判断是否是等级考试
//        if (type.getCertLevel().equals(1)) {
//
//            Integer acPass = pacProSkillCert.getAcPass();
//            if (acPass == null) {
//                throw new BaseException("请选择技能证书等级考试是否通过");
//            }
//
//            BigDecimal acScore = pacProSkillCert.getAcScore();
//            if (acScore == null) {
//                throw new BaseException("请填写技能证书等级考试成绩");
//            }
//        }

    }
}




